Cargamos nuestros paquetes que requeriremos

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(scales)
## 
## Adjuntando el paquete: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor
library(plotly)
## 
## Adjuntando el paquete: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout

Cargamos el archivo que analizaremos

datos <- read_csv("Vehiculos Registrados Jalisco.csv")
## Rows: 38 Columns: 47
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): Entidad, Municipio, Indicador
## dbl (44): 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Vemos las primeras filas de nuestra tabla

head(datos)
## # A tibble: 6 × 47
##   Entidad Municipio   Indicador `1980` `1981` `1982` `1983` `1984` `1985` `1986`
##   <chr>   <chr>       <chr>      <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
## 1 Jalisco Ameca       "Vehicul…   1762   2193   2529   2804   2944   2968   3117
## 2 Jalisco Arandas     "Veh\xed…   2000   2135   2814   3009   5614   4528   4749
## 3 Jalisco Atotonilco… "Veh\xed…   1826   1967   2352   2570   2702   2937   3091
## 4 Jalisco Chapala     "Veh\xed…    848   1049   1385   1554   1944   2053   2143
## 5 Jalisco Cihuatlan   "Veh\xed…   1223   1481   1684   1795   2096   2243   2366
## 6 Jalisco Cocula      "Veh\xed…    629    727    871    959   1219   1335   1568
## # ℹ 37 more variables: `1987` <dbl>, `1988` <dbl>, `1989` <dbl>, `1990` <dbl>,
## #   `1991` <dbl>, `1992` <dbl>, `1993` <dbl>, `1994` <dbl>, `1995` <dbl>,
## #   `1996` <dbl>, `1997` <dbl>, `1998` <dbl>, `1999` <dbl>, `2000` <dbl>,
## #   `2001` <dbl>, `2002` <dbl>, `2003` <dbl>, `2004` <dbl>, `2005` <dbl>,
## #   `2006` <dbl>, `2007` <dbl>, `2008` <dbl>, `2009` <dbl>, `2010` <dbl>,
## #   `2011` <dbl>, `2012` <dbl>, `2013` <dbl>, `2014` <dbl>, `2015` <dbl>,
## #   `2016` <dbl>, `2017` <dbl>, `2018` <dbl>, `2019` <dbl>, `2020` <dbl>, …

Nombramos una variable que almacene todos los años (1980-2023)

Año <- c(1980:2023)

Transformamos nuestros datos a un formato largo

datos_largo <- datos %>% 
        pivot_longer(
                cols = matches("^\\d{4}$"),
                names_to = "Año",
                values_to = "Total"
        ) %>% 
        mutate(
                Año = as.integer(Año),
                Total = na_if(Total, 0),
                Total = as.numeric(Total)
        )

Filtraremos solo los municipios de la ZMG

municipios_meta <- c("Guadalajara", "Zapopan", "San Pedro Tlaquepaque", "Tonala", "Tlajomulco de Zuniga")

datos_filtrados <- datos_largo %>% 
        filter(Municipio %in% municipios_meta)

Creamos una gráfica donde crearemos una línea del tiempo

grafica <- ggplot(datos_filtrados, aes(x = Año, y = Total, color = Municipio)) +
        geom_line(linewidth = 1.2, na.rm = TRUE) +
        geom_point(size = 1.5, na.rm = TRUE, aes(text = paste0(
                "Municipio: ", Municipio, "<br>",
                "Año: ", Año, "<br>",
                "Total: ", scales::comma(Total)
        ))) +
        labs(title = "Evolución de vehículos registrados (1980-2023)",
             subtitle = "Municipios del AMG",
             caption = "Fuente: Insituto de Información Estadistica y Geografica de Jalisco",
             x = "Año",
             y = "Total registrado") +
        scale_y_continuous(labels = label_comma()) +
        theme_minimal()
## Warning in geom_point(size = 1.5, na.rm = TRUE, aes(text = paste0("Municipio:
## ", : Ignoring unknown aesthetics: text

Nuestra linea del tiempo será interactiva, si posamos nuestro mouse en alguno de los puntos, nos brindará la información sobre el municipio, año y cantidad de vehiculos registrados.

grafica_interactiva <- ggplotly(grafica, tooltip = "text")
grafica_interactiva

Nombramos las variables que utilizaremos para agrupar el numero maximo y minimo de vehiculos registrados

registro_max <- datos_filtrados %>%
        group_by(Año) %>%
        filter(Total == max(Total, na.rm = TRUE)) %>%
        ungroup()

registro_min <- datos_filtrados %>%
        group_by(Año) %>%
        filter(Total == min(Total, na.rm = TRUE)) %>%
        ungroup()

Agregamos puntos para el municipio con mayores vehiculos registrados por año

grafica_max <- grafica +
        geom_point(data = registro_max, aes(x = Año, y = Total, color = Municipio), 
                   size = 3, shape = 17, color = "red") +
        labs(title = "Municipios con mayor registro de vehículos (1980-2023)",
             caption = "Fuente: Insituto de Información Estadistica y Geografica de Jalisco")

Agregamos puntos para el municipio con menores vehiculos registrados por año

grafica_min <- grafica +
        geom_point(data = registro_min, aes(x = Año, y = Total, color = Municipio), 
                   size = 3, shape = 17, color = "blue") +
        labs(title = "Municipios con menor registro de vehículos (1980-2023)",
             caption = "Fuente: Insituto de Información Estadistica y Geografica de Jalisco")

Convertimos nuestras gráficas de manera que tambien sean interactivas

Mostramos el grafico con el municipio con el mayor registro de vehiculos

grafica_max_interactiva <- ggplotly(grafica_max, tooltip = "text")
grafica_max_interactiva

Mostramos el grafico con el municipio con el menor registro de vehiculos

grafica_min_interactiva <- ggplotly(grafica_min, tooltip = "text")
grafica_min_interactiva